package com.cntaiping.workutil.report2;


import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

public class CsvExportUtil {

    /**
     * CSV文件列分隔符
     */
    private static final String CSV_COLUMN_SEPARATOR = ",";

    /**
     * CSV文件行分隔符
     */
    private static final String CSV_ROW_SEPARATOR = "\r\n";

    public static void doExport(List<Map<String, Object>> dataList, String titles, String keys, OutputStream os) throws IOException {

        //保证线程安全
        StringBuffer buffer = new StringBuffer();

        String[] titleArr = null;
        String[] keyArr = null;

        titleArr = titles.split(",");
        keyArr = keys.split(",");

        //组装表头
//        for (String title : titleArr) {
//            buffer.append(title).append(CSV_COLUMN_SEPARATOR);
//        }
//        buffer.append(CSV_ROW_SEPARATOR);

        //组装数据
        if (!CollectionUtils.isEmpty(dataList)) {
            for (Map<String, Object> data : dataList) {
                for (String key : keyArr) {
                    buffer.append(data.get(key)).append(CSV_COLUMN_SEPARATOR);
                }
                buffer.append(CSV_ROW_SEPARATOR);
            }
        }
        //写出响应
        os.write(buffer.toString().getBytes("GBK"));
        os.flush();
    }


    public static void responseSetProperties(String fileName, HttpServletResponse response) throws UnsupportedEncodingException {

        //设置文件后缀
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
        String fn = fileName + sdf.format(new Date()) + ".csv";
        //读取字符编码
        String utf = "UTF-8";

        //设置响应
        response.setContentType("application/ms-txt.numberformat:@");
        response.setCharacterEncoding(utf);
        response.setHeader("Pragma", "public");
        response.setHeader("Cache-Control", "max-age=30");
        response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fn, utf));
    }
/**
 * 这里是使用response下载csv的使用案例
 */
//    public static void main(String[] args) {
//        public Map<String, Object> downloadCSV (HttpServletResponse response, List < TempVo > dataList){
//            Map<String, Object> resultMap = new HashMap<>();
//            List<Map<String, Object>> dataListMap = TempVoFieldValue(dataList);
//
//            //构造导出数据结构
//            String titles = "模块名,系统名称,接入功能,功能id(api_id),调用量,调用量2,失败次数,失败次数2,最小时间,平均时间,最大时间,系统id(app_id),业务方";
//            logger.info("csv文件导出标题:{}", titles);
//            //设置每列字段
//            String keys = "module,appName,interfaceName,apiId,num,num2,failNum,failNum2,minTime,avgTime,maxTime,appId,busiDept";
//            logger.info("csv文件标题对应的字段:{}", keys);
//            //设置导出文件前缀
//            String fName = "aimanager_";
//            //导出文件
//
//            try {
//                OutputStream os = response.getOutputStream();
//                CsvExportUtil.responseSetProperties(fName, response);
//                CsvExportUtil.doExport(dataListMap, titles, keys, os);
//                os.close();
//                logger.info("csv文件导出成功,共 {} 条", dataListMap.size() - 1);
//                resultMap.put("result", "success");
//                return resultMap;
//            } catch (IOException e) {
//                e.printStackTrace();
//                logger.error("导出失败{}", e.getMessage());
//                resultMap.put("result", "failed");
//                resultMap.put("message", e.getMessage());
//                return resultMap;
//            }
//        }
//
//
//    }

}
